import type { Component } from 'vue';
import type { RouteRecordRaw } from 'vue-router';

/**
 * 已废弃
 */

// 模块类型
type ImportMetaGlob = {
  [key: string]: () => Promise<{ default: Component }>;
};

// 获取【layouts文件】信息
const layouts = import.meta.glob<ImportMetaGlob>('../layouts/*.vue', { eager: true });

// 获取【views文件】信息
const views = import.meta.glob<ImportMetaGlob>('../views/**/index.vue', { eager: true });

/**
 * 动态获取布局组件路由信息
 * @returns {RouteRecordRaw[]}
 */
function getRoutes() {
  // 动态获取的路由信息
  const layoutRouters: RouteRecordRaw[] = [];

  Object.entries(layouts).forEach(([file, module]) => {
    const route = mapFilesToRoutes(file, module);
    route.children = getChildrenRoutes(route);
    layoutRouters.push(route);
  });

  return layoutRouters;
}

/**
 * 动态获取【views】文件下,子页面组件路由信息
 * @returns {RouteRecordRaw[]}
 */
function getChildrenRoutes(layoutRoute: RouteRecordRaw) {
  const childrenRouters: RouteRecordRaw[] = [];

  Object.entries(views).forEach(([file, module]) => {
    if (file.includes(`../views/${layoutRoute.name as string}`)) {
      const route = mapFilesToRoutes(file, module);
      childrenRouters.push(route);
    }
  });

  return childrenRouters;
}

/**
 * 根据文件信息获取组件路由信息
 * @returns {RouteRecordRaw}
 */
function mapFilesToRoutes(file: string, module: { [key: string]: any }) {
  const name = file.replace(/.+layouts\/|.+views\/|\.vue/gi, '');
  const route: RouteRecordRaw = {
    name: name.replace(/\//g, '.'),
    path: `/${name}`,
    component: module.default,
    children: [],
  };
  return Object.assign(route, module.default?.route);
}

export default getRoutes();
